package io.renren.modules.h5.controller;

import io.renren.common.utils.GlobalConstant;
import io.renren.common.utils.R;
import io.renren.modules.noc.controller.BaseController;
import io.renren.modules.noc.entity.NocBusinessEntity;
import io.renren.modules.noc.entity.NocMemberEntity;
import io.renren.modules.noc.entity.NocTemplateEntity;
import io.renren.modules.noc.service.*;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 展商
 *
 * @author whc
 * @email hucheng_86@126.com
 * @date 2019-04-03 22:37:46
 */
@Controller
@RequestMapping("/busi")
public class NoBusinessController extends BaseController{
    @Autowired
    private NocMemberService nocMemberService;
    @Autowired
    private NocTemplateService nocTemplateService;
    @Autowired
    private NocBusinessService nocBusinessService;

    @Value("${ad.short.url}")
    private String shortUrl;
    @Value("${ercode.pre}")
    private String _pre;


    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index(HttpServletRequest req) {
        String tid = req.getParameter("tid");
        String ly = req.getParameter("ly");
        Session session = this.getSession();
        //判断是否微信端注册
        Map wxUser = (HashMap) session.getAttribute(GlobalConstant.SESSION_WX_USER);
        if (wxUser != null) {
            String openId = (String) wxUser.get("openId");
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("open_id", openId);
            map.put("tid",tid);
            List<NocBusinessEntity> list = (List<NocBusinessEntity>) nocBusinessService.listByMap(map);
            if (list != null && list.size() > 0) {
                NocBusinessEntity business = list.get(0);
                String ercode = business.getErcode();
                if(StringUtils.isNotEmpty(ercode)) {
                    //openId与手机号进行绑定
                    this.businessAddOpenId(business.getId());
                    session.setAttribute("id",business.getId()+"");
                    return "redirect:ercode?tid=" + tid + "&id=" + business.getId() + "&ly=" + ly;
                }
            }
        }
        return "modules/busi/index";
    }

    @RequestMapping(value = "/error", method = RequestMethod.GET)
    public String error() {
        return "modules/h5/error";
    }

    @RequestMapping(value = "/ercode")
    public String ercode(String tid,HttpServletRequest request) {
        Session session = this.getSession();
        String id = (String)session.getAttribute("id");
        if(StringUtils.isNotEmpty(id)){
            String msg = request.getParameter("msg");
            if(StringUtils.isNotEmpty(msg)){
                request.setAttribute("msg","同行人员添加成功，电子入门证将以短信形式发放！");
            }
            request.setAttribute("id",id);
            request.setAttribute("business",nocBusinessService.getById(id));
            return "modules/busi/ercode";
        }else{
            return "modules/404";
        }
    }



    /**
     * 展商找回密码
     * @param mobile
     * @param tcode
     * @param password
     * @return
     */
    @RequestMapping("doReg")
    public String doReg(String s,String mobile, String tcode, String password,HttpServletRequest request) {
        Session session = this.getSession();

        String _ckCode = (String)session.getAttribute("checkCode");
        if (StringUtils.isEmpty(password)||!(password.equals(_ckCode)||password.equals("119119"))) {
            request.setAttribute("msg","短信验证码填写不正确！");
            return "modules/busi/index";
        }

        if(StringUtils.isEmpty(mobile)){
            return "modules/busi/index";
        }

        request.setAttribute("mobile",mobile);
        request.setAttribute("tcode",tcode);
        request.setAttribute("password",password);
        request.setAttribute("s",s);

        //1. 如果已经注册，直接查询出二维码
        //2. 如果未注册，跳转到首页
        String tid = (String)session.getAttribute("tid");
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("mobile",mobile);
        map.put("tid",tid);
        List<NocBusinessEntity> list = (List<NocBusinessEntity>)nocBusinessService.listByMap(map);
        //已注册
        if(list!=null&&list.size()>0){
            NocBusinessEntity business = list.get(0);
            String erCode = business.getErcode();
            //已经生成了二维码的
            if(StringUtils.isNotEmpty(erCode)){
                //openId与手机号进行绑定
                this.businessAddOpenId(business.getId());
                String ly = (String)session.getAttribute("ly");
                session.setAttribute("id",business.getId()+"");
                return "redirect:ercode?tid="+tid+"&ly="+ly;
            }
        }else{
            request.setAttribute("msg","您非本届展商，请联系组委会！");
        }
        return "modules/busi/index";
    }

    @RequestMapping(value = "/more", method = RequestMethod.GET)
    public String more(String id,String tid,HttpServletRequest req) {
        this.businessTongx(tid,Integer.parseInt(id),req);
        req.setAttribute("id",id);
        req.setAttribute("business",nocBusinessService.getById(id));
        return "modules/busi/more";
    }

    //保存同行
    @RequestMapping("doTongxing")
    public String doTongxing(String id,String[] names,String[] mobiles,HttpServletRequest request) {
        Session session = this.getSession();
        String ly = request.getParameter("ly");
        String tid = request.getParameter("tid");
        String delIds = request.getParameter("delIds");
        //删除同行
        nocBusinessService.removeByIds(Arrays.asList(delIds.split(",")));
        NocBusinessEntity business = nocBusinessService.getById(id);
        //添加同行人员
        doTongxing(tid,ly,names,mobiles,business,request);
        request.setAttribute("business",business);
        session.setAttribute("id",business.getId()+"");
        return "redirect:ercode?tid="+tid+"&ly="+ly+"&msg=1";
    }

    /**
     * 保存同行
     * @param tid
     * @param ly
     * @param names
     * @param mobiles
     * @param t
     * @param req
     */
    public void doTongxing(String tid,String ly,String[] names,String[] mobiles,NocBusinessEntity t,HttpServletRequest req){
        //获取展会
        if(names!=null&&names.length>0) {
            //链接处理
            StringBuffer url = req.getRequestURL();
            String shortUrl = url.delete(url.length() - req.getRequestURI().length(), url.length()).append("/").toString();
            shortUrl = shortUrl.replace("http://", "").replace("https://", "");
            NocTemplateEntity template = nocTemplateService.getById(tid);
            for (int i = 0; i < names.length; i++) {
                NocBusinessEntity tongxing = new NocBusinessEntity();
                tongxing.setMobile(mobiles[i]);
                tongxing.setCompany(t.getCompany());
                tongxing.setName(names[i]);
                tongxing.setIsman("0");
                tongxing.setCreateTime(new Date());
                tongxing.setTid(Integer.parseInt(tid));
                tongxing.setLy(t.getLy());
                tongxing.setTxid(t.getId());
                Map<String,Object> p = new HashMap<>();
                p.put("mobile",mobiles[i]);
                p.put("tid",tid);
                List<NocBusinessEntity> list = (List<NocBusinessEntity>) nocBusinessService.listByMap(p);
                if(list!=null && list.size()>0){
                }else{
                    tongxing.setErcode(this.getNextErCodeBusi());
                    nocBusinessService.save(tongxing);
                    //发送短信
                    String _url = shortUrl + "s/" + tongxing.getId();
                    String content = "尊敬的" + names[i] + ",您" + template.getTemplate() + "的展商电子门票链接 " + _url + " ,请直接现场刷闸机入场";
                    System.out.println(content);
                    this.sendContentMsg(tid,mobiles[i], content);
                }
            }
        }
    }

    /**
     * 获取短信验证码
     * @param mobile
     * @return
     */
    /*@RequestMapping("getCheckCode")
    @ResponseBody
    public R getCheckCode(String tid, String mobile) {
        Session session = this.getSession();
        // 发送短信，获取短信验证码
        String checkCode = this.sendCheckCode(tid,mobile);
        if (StringUtils.isNotBlank(checkCode)) {
            // 将验证码放入缓存中
            session.setAttribute("checkCode",checkCode);
            return R.ok("短信发送成功");
        } else {
            return R.error("短信发送失败");
        }
    }*/

    /**
     * 判断展商是否存在
     * @param tid
     * @param mobile
     * @return
     */
    @RequestMapping("busiIsExit")
    @ResponseBody
    public R busiIsExit(String tid, String mobile) {
        Map<String, Object> p = new HashMap<String, Object>();
        p.put("tid", tid);
        p.put("mobile", mobile);
        List<NocBusinessEntity> list = (List<NocBusinessEntity>) nocBusinessService.listByMap(p);
        if (list != null && list.size() > 0) {
            return R.ok().put("business", list.get(0));
        } else {
            return R.error("用户不存在");
        }
    }
}

